package models

import (
	"errors"
	"github.com/astaxie/beego/orm"
)

type GoodsKind struct {
	GoodsKindId     int `pk:"ai"`
	GoodsKindName   string
	GoodsStoreId    int
	SystemKindId    int
	GoodsKindParent int
	Children        []GoodsKind `ignore:"true"`
}

func GetAllParentGoodKindByStoreId(storeId int) ([]GoodsKind, error) {
	if storeId == 0 {
		return nil, errors.New("store id is nil")
	} else {
		newOrm := orm.NewOrm()
		sql := QueryByEqualField(GoodsKind{}, "GoodsStoreId")
		sql = sql + " and goods_kind_parent is null"
		var kinds []GoodsKind
		_, e := newOrm.Raw(sql, storeId).QueryRows(&kinds)
		if e != nil {
			panic(e)
		}
		for i, _ := range kinds {
			kinds[i].Children, e = getAllChildrenByParentId(kinds[i].GoodsKindId)
			if e != nil {
				return nil, e
			}
		}
		return kinds, nil
	}
}
func GetAllGoodKindByStoreId(storeId int) []GoodsKind {
	newOrm := orm.NewOrm()
	sql := QueryByEqualField(GoodsKind{}, "GoodsStoreId")
	var kinds []GoodsKind
	_, e := newOrm.Raw(sql, storeId).QueryRows(&kinds)
	if e != nil {
		panic(e)
	}
	return kinds
}
func getAllChildrenByParentId(parentId int) ([]GoodsKind, error) {
	var childrens []GoodsKind
	newOrm := orm.NewOrm()
	sql := QueryByEqualField(GoodsKind{}, "GoodsKindParent")
	_, e := newOrm.Raw(sql, parentId).QueryRows(&childrens)
	if e != nil {
		panic(e)
		return nil, e
	} else {
		return childrens, nil
	}
}
